/*******************************************************************************
 * Copyright (c) 2010 Torkild U. Resheim
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Torkild U. Resheim - initial API and implementation
 *******************************************************************************/
package no.resheim.buildmonitor.ui.views;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.dialogs.FilteredTree;
import org.eclipse.ui.dialogs.PatternFilter;

public class ImprovedFilteredTree extends FilteredTree {

	private final boolean useNewLook;

	public ImprovedFilteredTree(Composite parent, int treeStyle,
			PatternFilter filter, boolean useNewLook) {
		super(parent, treeStyle, filter, useNewLook);
		this.useNewLook = useNewLook;
	}

	@Override
	protected void init(int treeStyle, PatternFilter filter) {
		// TODO Auto-generated method stub
		super.init(treeStyle, filter);
		System.out.println(filter);
	}

	@Override
	protected Text doCreateFilterText(Composite parent) {
		if (!useNewLook || _useNativeSearchField(parent)) {
			final Text text = new Text(parent, SWT.SINGLE | SWT.BORDER
					| SWT.SEARCH | SWT.ICON_CANCEL | SWT.ICON_SEARCH);
			return text;
		}
		return new Text(parent, SWT.SINGLE);
	}

	private static Boolean useNativeSearchField;

	private static boolean _useNativeSearchField(Composite composite) {
		if (useNativeSearchField == null) {
			useNativeSearchField = Boolean.FALSE;
			Text testText = null;
			try {
				testText = new Text(composite, SWT.SEARCH | SWT.ICON_CANCEL
						| SWT.ICON_SEARCH);
				useNativeSearchField = Boolean
						.valueOf((testText.getStyle() & SWT.ICON_CANCEL) != 0);
			} finally {
				if (testText != null) {
					testText.dispose();
				}
			}

		}
		return useNativeSearchField.booleanValue();
	}

}
